package cool.taomu.toolkit.cacheable

import com.google.auto.service.AutoService
import com.google.common.cache.Cache
import com.google.inject.AbstractModule
import com.google.inject.TypeLiteral
import com.google.inject.matcher.Matchers
import com.google.inject.name.Names
import cool.taomu.toolkit.TaomuConfigure
import cool.taomu.toolkit.platform.inter.IPlatform
import java.util.Map
import com.google.inject.multibindings.OptionalBinder
import com.google.inject.Key

@AutoService(IPlatform)
class CacheablePlugin implements IPlatform {

    override note() {
        "Cacheable插件"
    }

    override packages() {
    }

    override module(TaomuConfigure config) {
        new AbstractModule() {
            override void configure() {
                config.binder("taomu.cacheable", [
                    if (it instanceof Map) {
                        if (it.containsKey("type") && (it.get("type") as String).equalsIgnoreCase("guava")) {
                            OptionalBinder.newOptionalBinder(
                                binder(),
                                Key.get(
                                    new TypeLiteral<Map<String, Object>>() {
                                    },
                                    Names.named("taomu.cacheable.config.guava")
                                )
                            ).setDefault.toInstance(it)
                            OptionalBinder.newOptionalBinder(binder(), new TypeLiteral<Cache<String, byte[]>>() {
                            }).setDefault.toProvider(GuavaCacheProvider)
                            OptionalBinder.newOptionalBinder(
                                binder(),
                                Key.get(
                                    ICacheService,
                                    Names.named("taomu.cacheable.name.guava")
                                )
                            ).setDefault.to(GuavaCacheService).asEagerSingleton
                        }
                    }
                ])
                var CachingInterceptor after = new CachingInterceptor();
                requestInjection(after);
                bindInterceptor(
                    Matchers.any(),
                    Matchers.annotatedWith(Cacheable),
                    after
                );
               
            }
        }
    }

    override start() {
    }

    override init() {
    }

}
